<?php
/**
 * PhpStorm
 * User: zucheng
 * Date: 2019/3/23
 */

namespace App\Http\Controllers\Api\V1;

use App\Models\Member;
use App\Services\UmengService;
use DB;
use App\Models\Notice;
use App\Models\NoticeMessage;
use Validator;
use App\Http\Controllers\Api\ApiController;
use App\Models\Message;
use Illuminate\Http\Request;

class MessageController extends ApiController
{
    /**
     * 获取消息列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function msgList(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_uuid' => 'required|size:36',
                'page'      => 'required|integer',
                'limit'     => 'required|integer',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $fields = [
                'id as message_id',
                'title',
                'content',
                'read',
                'send_uuid',
                'created_at'
            ];

            $oSql = Message::select($fields)
                ->where('accept_uuid', $request->get('user_uuid'));

            $read = $request->get('read') ?? 0;
            if ($read) {
                $oSql->where('read', $read);
            }

            $res = $oSql->paginate($request->get('limit', self::DEFAULT_PAGE_LIMIT))
                ->toArray();

            return $this->table($res['data'], $res['total']);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 删除系统消息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delSystemMsg(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_uuid' => 'required|size:36',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            Message::where('accept_uuid', $request->get('user_uuid'))
                ->where('send_uuid', '1')// 发送者uuid 为1 代表系统消息
                ->delete();

            return $this->success('删除成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 回复消息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function replyMsg(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_uuid'   => 'required|size:36',
                'title'       => 'required|min:2|max:60',
                'content'     => 'required|min:2|max:500',
                'accept_uuid' => 'required|size:36',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $data = [
                'title'       => $request->get('title'),
                'content'     => $request->get('content'),
                'accept_uuid' => $request->get('accept_uuid'),
                'send_uuid'   => $request->get('user_uuid'),
                'flag'        => Message::FLAG_FRONT_FRONT,
            ];
            Message::create($data);

            /**
             * 以下情况需要发送友盟推送，若推送失败则发送短信；若是接收人登录的是小程序，则直接发送短信:
             * 发单人 -> 司机
             * 司机 -> 发单人
             * 发货人/收货人 -> 司机
             * 司机 -> 发货人/收货人
             */
            $oMsgSender   = Member::query()->where('uuid', $request->get('user_uuid'))->where('status', 1)->firstOrFail();
            $oMsgReceiver = Member::query()->where('uuid', $request->get('accept_uuid'))->where('status', 1)->firstOrFail();
            if (
                ($oMsgSender->role_id == Member::ROLE_ORDER && $oMsgReceiver->role_id == Member::ROLE_DRIVER) ||
                ($oMsgSender->role_id == Member::ROLE_DRIVER && $oMsgReceiver->role_id == Member::ROLE_ORDER) ||
                (in_array($oMsgSender->role_id, [Member::ROLE_SHIPPER, Member::ROLE_RECEIVER]) && $oMsgReceiver->role_id == Member::ROLE_DRIVER) ||
                ($oMsgSender->role_id == Member::ROLE_DRIVER && in_array($oMsgReceiver->role_id, [Member::ROLE_SHIPPER, Member::ROLE_RECEIVER]))
            ) {
                $userPlatform = $oMsgReceiver->user_platform;
                if (!in_array($userPlatform, array_keys(Member::USER_PLATFORMS))) {
                    return $this->success();
                }

                if ($userPlatform == Member::USER_PLATFORM_WXXCX) {
                    // @todo 发送短信

                    return $this->success();
                }

                // 发送友盟推送
                try {
                    $pushType     = $oMsgReceiver->role_id == Member::ROLE_DRIVER ? 'driver' : 'owner';
                    $umengService = new UmengService($pushType);
                    switch ($userPlatform) {
                        case Member::USER_PLATFORM_ANDROID:
                            $params = [
                                'alias_type'  => 'user_alias',
                                'alias'       => $request->get('accept_uuid'),
                                "ticker"      => "系统通知",
                                "title"       => $request->get('title'),
                                "text"        => $request->get('content'),
                                "after_open"  => "go_app",
                                "description" => $request->get('title'),
                            ];
                            if ($oMsgSender->role_id == Member::ROLE_ORDER && $oMsgReceiver->role_id == Member::ROLE_DRIVER) {
                                $params['payload']['extra']['cust_type'] = 2; // type：2 跳转站内信页面 
                            }

                            $umengService->paramsBuilder($params)->androidCustomizedCast();
                            break;
                        case Member::USER_PLATFORM_IOS:
                            $params = [
                                'alert'       => [
                                    'title' => $request->get('title'),
                                    'body'  => $request->get('content'),
                                ],
                                'alias_type'  => 'user_alias',
                                'alias'       => $request->get('accept_uuid'),
                                "description" => $request->get('title'),
                            ];
                            if ($oMsgSender->role_id == Member::ROLE_ORDER && $oMsgReceiver->role_id == Member::ROLE_DRIVER) {
                                $params['payload']['cust_type'] = 2; // type：2 跳转站内信页面
                            }

                            $umengService->paramsBuilder($params)->iosCustomizedCast();
                            break;
                    }

                } catch (\Exception $e) {
                    // @todo 发送短信
                }

            }


            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 消息已读
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function readMsg(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_uuid'  => 'required|size:36',
                'message_id' => 'required|integer',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $message       = Message::where('accept_uuid', $request->get('user_uuid'))
                ->findOrFail($request->get('message_id'));
            $message->read = Message::READ_YES;

            $message->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 通知列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNoticeList(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_uuid' => 'required|size:36',
                'page'      => 'required|integer',
                'limit'     => 'required|integer',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $msg = Notice::with([
                'noticeMessage' => function ($query) {
                    $query->with('message');
                }
            ])->where('send_uuid', $request->get('user_uuid'))
                ->paginate($request->get('limit', self::DEFAULT_PAGE_LIMIT))
                ->toArray();
            if ($msg['total'] == 0) {
                return $this->table();
            }

            $data = [];
            foreach ($msg['data'] as $key => $item) {
                $data[$key]['n_id']    = $item['id'];
                $data[$key]['title']   = $item['title'];
                $data[$key]['content'] = $item['content'];
                $unreadNum             = 0;
                $readNum               = 0;
                foreach ($item['notice_message'] as $messages) {
                    if ($messages['message']['read'] == Message::READ_YES) {
                        $readNum++;
                    } else {
                        $unreadNum++;
                    }
                }
                $data[$key]['read_num']   = $readNum;
                $data[$key]['unread_num'] = $unreadNum;
            }

            return $this->table($data, $msg['total']);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 新增通知
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addNotice(Request $request)
    {
        DB::beginTransaction();
        try {
            $validator = Validator::make($request->all(), [
                'user_uuid'    => 'required|size:36',
                'title'        => 'required|min:2|max:60',
                'content'      => 'required|min:2|max:500',
                'accept_uuids' => 'required',
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            // 通知记录
            $noticeData = [
                'title'     => $request->get('title'),
                'content'   => $request->get('content'),
                'send_uuid' => $request->get('user_uuid')
            ];
            $notice     = Notice::create($noticeData);

            // 消息记录
            $acceptUuids = explode(',', $request->get('accept_uuids'));
            $ret         = [];
            foreach ($acceptUuids as $key => $acceptUuid) {
                $msgData = [
                    'title'       => $request->get('title'),
                    'content'     => $request->get('content'),
                    'accept_uuid' => $acceptUuid,
                    'send_uuid'   => $request->get('user_uuid'),
                    'flag'        => Message::FLAG_FRONT_FRONT,
                ];
                $msg     = Message::create($msgData); // 消息表记录

                // 通知消息关联表记录
                NoticeMessage::create([
                    'notice_id'  => $notice->id,
                    'message_id' => $msg->id,
                ]);

                $ret[$key]['accept_uuid'] = $acceptUuid;
                $ret[$key]['accept_code'] = 0;
            }

            DB::commit();

            return $this->success('success', $ret);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
    }

}